﻿using System;
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

using Agile.Service;
using Agile.Service.Rbac;

namespace ConsoleApp
{
    public class HrCollectionPageButtons
    {
        private static readonly IMenuElementService menuElementDal = new MenuElementService();
        private static readonly IMenuService menuDal = new MenuService(new MenuElementService());
        private static string baseUrl = "http://localhost:85";
        public static void Run()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("*******开始采集人事系统页面命令***************");
            CollectionPageButtons();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("*******采集人事系统页面命令结束***************");
        }
        private static void CollectionPageButtons()
        {
            var menus = menuDal.GetByAll("Name NOT IN('系统结构','健康检查','图标管理') AND ParentID<>'00000000-0000-0000-0000-000000000000'");
            foreach (var menu in menus)
            {
                var uri = menu.Url.Split("/");
                if (uri.Length <= 1) continue;
                string testContent = GetPageContent(baseUrl + menu.Url);
                if (!string.IsNullOrWhiteSpace(testContent))
                {
                    // <a\b[^>]+\bid="NF-([^"]*)"[^>]*>([\s\S]*?)</a>
                    string pattern = @"<a\b[^>]+\bid=""NF-([^""]*)""[^>]*>([\s\S]*?)</a>";
                    Regex s = new Regex(pattern);
                    if (s.IsMatch(testContent))
                    {
                        foreach (Match item in s.Matches(testContent))
                        {
                            //<a id="NF-add" authorize="yes" class="btn btn-primary dropdown-text" onclick="AddBatch()"><i class="glyphicon glyphicon-plus"></i>新增</a>
                            string tempstr = item.Groups[0].Value;
                            MenuElement pageButton = new MenuElement();
                            pageButton.ModuleId = menu.ID;
                            pageButton.Name = Utils.GetChineseWord(tempstr);
                            pageButton.DomId = GetBtnInfo(tempstr, @"id=.+?""", "id=");
                            pageButton.Icon = GetBtnInfo(tempstr, @"<i\b[^>]+\bclass=.+?""", "<i").Replace("class=", "");
                            pageButton.Script = GetBtnInfo(tempstr, @"onclick=.+?""", "onclick=");

                            var flg = menuElementDal.Exist(p => p.Name == pageButton.Name && p.ModuleId == menu.ID);
                            if (!flg)
                            {
                                menuElementDal.Add(pageButton);
                                Console.WriteLine("***" + pageButton.ToString());
                            }
                        }
                    }
                }
            }
        }
        private static string GetBtnInfo(string m_outstr, string pattern, string filter = "")
        {
            string tempstr = "";
            Regex s = new Regex(pattern);
            if (s.IsMatch(m_outstr))
            {
                foreach (Match item in s.Matches(m_outstr))
                {
                    tempstr = item.Groups[0].Value;
                    tempstr = tempstr.Replace(@"""", "");
                    tempstr = tempstr.Replace(filter, "");
                    break;
                }
            }
            return tempstr;
        }
        private static string GetPageContent(string url)
        {
            try
            {
                WebClient myClient = new WebClient();
                myClient.Headers.Add(HttpRequestHeader.Cookie, ".agile.session=CfDJ8C1WFGZ4%2B5NCv%2FVnzc19BDuH4t%2B2LS5JKVCrcyAzBBwbXczi1LXoaubWyjPpjSJw11DMhhhVorlV7FwQ0U7iMVTEcwtkoPM5Kz3vAuhox%2BqqborBMjYsmeAFqwoo3Go6%2BhGUwR9z9B0w8XEb7WxUt7ae8bojjpxRYU099TUeFIsa");
                myClient.Headers.Add(HttpRequestHeader.Cookie, ".agile.authentication=CfDJ8C1WFGZ4-5NCv_Vnzc19BDuWwaNieTM2EoXHDQFCNm9O9D7kmyIg1hEAlTcv-6Ys8V33Vh-EALjPZRI1XhfqrQPzbZOHc_WpFoYc2gbHLsoqs0sOl9kFTpTAIyZRBTsfEmdxa_3m6aJoUHMCYGUskWKXsAf9PAm2JZS9odGmBnwCCI4qNoVMRi8NSJCJmjFUZsXJoEWScKCzvjj6Xe-PkwLHLJTUPCW7P7MS6y712tlbJeyxIiv4vbuQEguki-RxgkfxLLzIKMSNpmk3gVfDgFJCgXjcWa9qrvuOks2vNHC8P_emJbPQh5bJ7fAucqxKr_bpsQQUvWIgjnLlyrVcZPX8ySEXGtQb4nOkqi246KGd3VQbgusmAbea6XPGAMXnJZM9gFJpY2zEqYa5nGNe5wtFBURNij11AC35JNktNGSKJaiEn1tq2_pK_fbGRuH_XdBeolG8pAWUut2VWn8NKCELCGBUsWI3hvFzEQWIvfUQTvhoyrqkUaSAYbOBc1ArbSaRCgrVenVCohogjZSv77E");
                myClient.Credentials = CredentialCache.DefaultCredentials;
                var pageData = myClient.DownloadData(url);
                string pageHtml = Encoding.Default.GetString(pageData);
                return getFirstNchar(pageHtml);
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 此私有方法从一段HTML文本中提取出一定字数的纯文本
        /// </summary>
        /// <param name="instr">HTML代码</param>
        /// <returns>纯文本</returns>
        private static string getFirstNchar(string instr)
        {
            string m_outstr = instr.Clone() as string;
            m_outstr = new Regex(@"(?m)<script[^>]*>(\w|\W)*?</script[^>]*>", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, string.Empty);
            m_outstr = new Regex(@"(?m)<style[^>]*>(\w|\W)*?</style[^>]*>", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, string.Empty);
            m_outstr = new Regex(@"(?m)<link[^>]*>(\w|\W)*?[^>]*>", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, string.Empty);
            m_outstr = new Regex(@"<iframe[\s\S]+</iframe *>", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, string.Empty);
            m_outstr = new Regex(@"<frameset[\s\S]+</frameset  *>", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, string.Empty);
            m_outstr = new Regex(@"-->", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, string.Empty);
            m_outstr = new Regex(@"<!--.*", RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr, string.Empty);
            m_outstr = new Regex(@"(&nbsp;)+").Replace(m_outstr, "");
            m_outstr = new Regex(@"(\r\n\r\n)+").Replace(m_outstr, "");

            return m_outstr;
        }




    }
}
